import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  /*name: '',
  avatar: '',
  introduction: '',
  roles: []*/
  userId:'',
  userName:'',
  userNickName:'',
  mobilePhone:'',
  email:'',
  avatar:'',
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USER : (state,user)=>{
    if(user){
      state.userId = user.userId
      state.userName = user.userName
      state.userNickName = user.userNickname
      state.mobilePhone = user.mobilePhone
      state.email = user.email
      state.avatar = user.avatar
    }
  }
  /*SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }*/
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: username, password: password }).then(response => {
        console.log('login',response)

        const result = response.result
          // token和用户信息存储到vuex
          commit('SET_TOKEN', result.token)

          // token存储到cookie用于免登录
          setToken(result.token)
          resolve()
      }).catch(err=>{
        reject(err)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      if(sessionStorage.getItem('userInfo') !== null){
        commit('SET_USER',JSON.parse(sessionStorage.getItem('userInfo')))
        // console.log('>>>从sessionStorage拿到用户信息')
        resolve()
      }else{
        getInfo().then(res=>{
          const result = res.result
          commit('SET_USER',result)
          sessionStorage.setItem('userInfo',JSON.stringify(result))
          // console.log('>>>从服务器拿到用户信息')
          resolve()
        }).catch(err=>{
          // 如果从服务器拿不到用户信息，就说明token过期了，抛出错误的同时清理过期token
          removeToken()
          reject(err)
        })
      }
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        resolve()
      }).catch(error => {
        console.log(error)
        reject(error)
      })
    })
  },
  frontLogOut({commit,state,dispatch}){
    return new Promise((resolve, reject) => {
      commit('SET_USER', null)
      removeToken()
      resetRouter()
      dispatch('tagsView/delAllViews', null, { root: true })
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
